package com.ruoyi.project.module.applicationProperty.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.module.application.mapper.ApplicationMapper;
import com.ruoyi.project.module.applicationProperty.domain.ApplicationProperty;
import com.ruoyi.project.module.applicationProperty.mapper.ApplicationPropertyMapper;
import com.ruoyi.project.module.group.domain.Group;
import com.ruoyi.project.module.group.service.IGroupService;
import com.ruoyi.project.module.groupProperty.domain.GroupProperty;
import com.ruoyi.project.module.groupProperty.service.IGroupPropertyService;
import com.ruoyi.project.module.task.mapper.TaskUtilsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * 应用属性 服务层实现
 * <br>
 * com.ruoyi.project.module.applicationProperty.service.ApplicationPropertyServiceImpl
 * <br>
 *
 * @author shoukaiseki
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 * @date 2019-01-14 13:18:25<br>
 */
@Service
public class ApplicationPropertyServiceImpl implements IApplicationPropertyService 
{

	static final Logger logger=LoggerFactory.getLogger(ApplicationPropertyServiceImpl.class);

	@Resource
	TaskUtilsMapper taskUtilsMapper;

	@Resource
	private ApplicationMapper applicationMapper;
	@Resource
	private ApplicationPropertyMapper applicationPropertyMapper;


	@Resource
	private IGroupService groupService;

	@Resource
	private IGroupPropertyService groupPropertyService;

	/**
     * 查询应用属性信息
     * 
     * @param configApplicationPropertyId 应用属性ID
     * @return 应用属性信息
     */
    @Override
	public ApplicationProperty selectApplicationPropertyById(Long configApplicationPropertyId)
	{
	    return applicationPropertyMapper.selectApplicationPropertyById(configApplicationPropertyId);
	}
	
	/**
     * 查询应用属性列表
     * 
     * @param applicationProperty 应用属性信息
     * @return 应用属性集合
     */
	@Override
	public List<ApplicationProperty> selectApplicationPropertyList(ApplicationProperty applicationProperty)
	{
	    return applicationPropertyMapper.selectApplicationPropertyList(applicationProperty);
	}
	
    /**
     * 新增应用属性
     * 
     * @param applicationProperty 应用属性信息
     * @return 结果
     */
	@Override
	public int insertApplicationProperty(ApplicationProperty applicationProperty)
	{
		Date currentDate = taskUtilsMapper.getCurrentDate();
		String userName = ShiroUtils.getUser().getLoginName();
		applicationProperty.setCreateBy(userName);
		applicationProperty.setCreateTime(currentDate);
		applicationProperty.setUpdateBy(userName);
		applicationProperty.setUpdateTime(currentDate);
		applicationProperty.setModify(1);
		ApplicationProperty parent = applicationPropertyMapper.selectApplicationPropertyById(applicationProperty.getParentId());
		if(parent!=null){
			applicationProperty.setAncestors(parent.getAncestors() + "," + parent.getParentId());
		}else {
			applicationProperty.setAncestors("0");
		}

		//获取应用id并设置
		applicationMapper.updateModify(applicationProperty.getConfigApplicationId(),true);
		return applicationPropertyMapper.insertApplicationProperty(applicationProperty);
	}
	
	/**
     * 修改应用属性
     * 
     * @param applicationProperty 应用属性信息
     * @return 结果
     */
	@Override
	public int updateApplicationProperty(ApplicationProperty applicationProperty)
	{

		Date currentDate = taskUtilsMapper.getCurrentDate();
		String userName = ShiroUtils.getUser().getLoginName();
		applicationProperty.setCreateBy(userName);
		applicationProperty.setCreateTime(null);
		applicationProperty.setUpdateBy(userName);
		applicationProperty.setUpdateTime(currentDate);
		applicationProperty.setModify(1);
		ApplicationProperty parent = applicationPropertyMapper.selectApplicationPropertyById(applicationProperty.getParentId());
		if(parent!=null){
			applicationProperty.setAncestors(parent.getAncestors() + "," + parent.getParentId());
		}else {
			applicationProperty.setAncestors("0");
		}

		//获取应用id并设置
		ApplicationProperty temp = selectApplicationPropertyById(applicationProperty.getConfigApplicationPropertyId());
		applicationMapper.updateModify(temp.getConfigApplicationId(),true);

	    return applicationPropertyMapper.updateApplicationProperty(applicationProperty);
	}

	/**
     * 删除应用属性对象
	 *
	 * 如果包含子级信息也将删除
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteApplicationPropertyByIds(String ids)
	{
		List<Long>idList= Lists.newArrayList();
		Long id=null;
		for (String parentId:ids.split(",")) {
			if(id==null){
				id=Long.parseLong(parentId);
			}
			idList.add(Long.parseLong(parentId));
			List<Long> chindsIdList = getChindsIdList(Long.parseLong(parentId));
			idList.addAll(chindsIdList);
		}


		List<String> idStrList = Lists.newArrayList();

		for (Long aLong : idList) {
			idStrList.add(String.valueOf(aLong));
		}
		logger.debug("idList={}",idList);
		if(logger.isDebugEnabled()){
			//此处不能用,变参形式,因为结果是数组结构
			logger.debug("idList={}",idStrList.toArray(new String[idStrList.size()]).toString());
		}

		ApplicationProperty temp = selectApplicationPropertyById(id);
		applicationMapper.updateModify(temp.getConfigApplicationId(),true);
		return applicationPropertyMapper.deleteApplicationPropertyByIds(idStrList.toArray(new String[idStrList.size()]));
	}


	public List<Long> getChindsIdList(Long parentId){
		List<Long> list = Lists.newArrayList();
		List<ApplicationProperty> applicationProperties = applicationPropertyMapper.selectApplicationPropertyByParentId(parentId);
		for (ApplicationProperty applicationProperty : applicationProperties) {
			Long configApplicationPropertyId = applicationProperty.getConfigApplicationPropertyId();
			list.add(configApplicationPropertyId);
			List<Long> chindsList = getChindsIdList(configApplicationPropertyId);
			list.addAll(chindsList);
		}
		return list;
	}


	@Override
	public boolean importGroupPropertySelective(Long configApplicationId, Long[] configGroupPropertyIds, String propertyPrefix) {
		ApplicationProperty applicationPropertyParent = getOrCreatedConfigApplicationPropertyByPropertyPrefix(configApplicationId, propertyPrefix);
		if(configGroupPropertyIds!=null) {
			for (Long configGroupPropertyId:configGroupPropertyIds) {
				GroupProperty groupPropertyTemp = groupPropertyService.selectGroupPropertyById(configGroupPropertyId);
				Group configGroup = groupService.selectGroupById(groupPropertyTemp.getConfigGroupId());
				ApplicationProperty configApplicationProperty = createConfigApplicationProperty(configApplicationId,applicationPropertyParent,configGroup, groupPropertyTemp);
			}

		}
		return false;
	}

	@Override
	public boolean importGroupProperty(Long configApplicationId,Long configGroupId,String propertyPrefix) {

		ApplicationProperty applicationPropertyParent = getOrCreatedConfigApplicationPropertyByPropertyPrefix(configApplicationId, propertyPrefix);
		Group configGroup = groupService.selectGroupById(configGroupId);

		importByConfigGroupId(configApplicationId,applicationPropertyParent,configGroup,0L);


		return false;
	}

	public void importByConfigGroupId(Long configApplicationId,ApplicationProperty applicationPropertyParent,Group configGroup,Long groupPropertyParentId){
	    Long configGroupId=configGroup.getConfigGroupId();
		GroupProperty groupProperty = new GroupProperty();
		groupProperty.setConfigGroupId(configGroupId);
		groupProperty.setParentId(groupPropertyParentId);
		List<GroupProperty> groupPropertyList = groupPropertyService.selectGroupPropertyList(groupProperty);

		//配置属性缓存,因为配置属性树结构,实际属性名跟父级使用 '.' 进行拼接
		Map<Long,String> cacheMap= Maps.newHashMap();
		Iterator<GroupProperty> iterator = groupPropertyList.iterator();
		while ( iterator.hasNext()) {
			GroupProperty groupPropertyTemp=iterator.next();
			Long configGroupPropertyId = groupPropertyTemp.getConfigGroupPropertyId();

			ApplicationProperty configApplicationProperty = createConfigApplicationProperty(configApplicationId,applicationPropertyParent,configGroup, groupPropertyTemp);
			importByConfigGroupId(configApplicationId,configApplicationProperty,configGroup,groupPropertyTemp.getConfigGroupPropertyId());
		}
	}

	public ApplicationProperty createConfigApplicationProperty(Long configApplicationId,ApplicationProperty applicationPropertyParent,Group configGroup,GroupProperty groupProperty){
		ApplicationProperty applicationProperty=new ApplicationProperty();
		applicationProperty.setConfigApplicationId(configApplicationId);
		applicationProperty.setPropKey(groupProperty.getPropKey());
		applicationProperty.setPropValue(groupProperty.getPropValue());
		applicationProperty.setConfigGroupId(groupProperty.getConfigGroupId());
		applicationProperty.setConfigGroupPropertyId(groupProperty.getConfigGroupPropertyId());
		applicationProperty.setParentId(applicationPropertyParent.getConfigApplicationPropertyId());
		applicationProperty.setDescription(groupProperty.getDescription());
		applicationProperty.setGroupType(configGroup.getGroupType());
		applicationProperty.setRemark(groupProperty.getRemark());

		String fullNameOfProperty = new StringBuilder(applicationPropertyParent.getFullNameOfProperty())
				.append(".").append(groupProperty.getPropKey()).toString();
		applicationProperty.setFullNameOfProperty(fullNameOfProperty);

		int i = insertApplicationProperty(applicationProperty);
		if(i!=1){
			throw new RuntimeException("新增应用配置失败");
		}


		return applicationProperty;
	}


	@Override
	public ApplicationProperty getOrCreatedConfigApplicationPropertyByPropertyPrefix(Long configApplicationId, String propertyPrefix) {
		ApplicationProperty applicationProperty = new ApplicationProperty();
		applicationProperty.setConfigApplicationId(configApplicationId);
		applicationProperty.setFullNameOfProperty(propertyPrefix);
		List<ApplicationProperty> applicationPropertyList = applicationPropertyMapper.selectApplicationPropertyList(applicationProperty);
		if(applicationPropertyList.isEmpty()){
			int index = propertyPrefix.lastIndexOf(".");
			applicationProperty = new ApplicationProperty();
			applicationProperty.setConfigApplicationId(configApplicationId);
			applicationProperty.setFullNameOfProperty(propertyPrefix);
			if(index==-1){
				applicationProperty.setPropKey(propertyPrefix);
				applicationProperty.setParentId(0L);
				int i = insertApplicationProperty(applicationProperty);
				if(i==1){
					return applicationProperty;
				}
			}else{
				ApplicationProperty applicationProperty1Parent = getOrCreatedConfigApplicationPropertyByPropertyPrefix(configApplicationId, propertyPrefix.substring(0, index));
				applicationProperty.setParentId(applicationProperty1Parent.getConfigApplicationPropertyId());
				applicationProperty.setPropKey(propertyPrefix.substring(index+1));
				int i = insertApplicationProperty(applicationProperty);
				if(i==1){
					return applicationProperty;
				}
			}
		}else{

			return applicationPropertyList.get(0);
		}
		return null;
	}


	@Override
	public Boolean hasChilds(Long parentId) {
		int childSize=applicationPropertyMapper.childSize(parentId);
		return childSize==0?false:true;
	}
}
